package edu.mju.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private final static Class<MyBatisUtil> MY_BATIS_UTIL_CLASS = MyBatisUtil.class;

    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * private修饰构造方法，不能通过new创建MyBatisUtil()。
     */
    private MyBatisUtil() {
    }

    /**
     * 创建SqlSessionFactory(工厂接口)
     *
     * @return SqlSessionFactory
     * @throws IOException
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        //加锁，防止多线程多次实例化SqlSessionFactory对象
        synchronized (MY_BATIS_UTIL_CLASS) {
            if (sqlSessionFactory != null) {
                return sqlSessionFactory;
            }
            //读取配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            try {
                //通过MyBatis的Resources对象getResourceAsStream方法返回在classpath作为Stream对象的资源
                inputStream = Resources.getResourceAsStream(resource);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            return sqlSessionFactory;
        }
    }

    /**
     * 获取SqlSession
     *
     * @return SqlSession
     * @throws IOException
     */
    public static SqlSession getSession() {
		if(sqlSessionFactory == null){
			getSqlSessionFactory();
		}
        return sqlSessionFactory.openSession();
    }
}
